import { createSlice, configureStore, createAsyncThunk } from "@reduxjs/toolkit"
// 创建异步切片函数
// 第一个参数时函数的名字可以随便叫
// 第二个参数是函数体，执行异步操作
// 注意：异步切片函数的返回值必须是一个promise对象，要写async
export const asyncFun = createAsyncThunk("mesSlice2/asyncFun", async (value) => {
    let res = await new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(value)
        }, 2000)
    })
    return res
})

let mesSlice = createSlice({
    name: "mesSlice",//命名
    initialState: { //初始值
        mes: "",
        num: 0
    },
    reducers: {//改变值
        addMes(state, action) {
            state.mes = action.payload
        },
        addNum(state, action) {
            state.num = state.num + action.payload
        },

    }
})

let mesSlice2 = createSlice({
    name: "mesSlice2",//命名
    initialState: { //初始值
        mes: "这是",
        num: 333,
        opp: 16
    },
    reducers: {//改变值
        addMes(state, action) {
            state.mes = action.payload
        },
        addNum(state, action) {
            state.num = state.num + action.payload
        },

    },
    extraReducers: (chunk) => {
        chunk.addCase(asyncFun.pending, () => {
            console.log("pending")
        })
        chunk.addCase(asyncFun.fulfilled, (state, action) => {
            state.num = state.num + 3
            console.log("fulfilled")
        })
    }
})

let store = configureStore({
    reducer: {
        mesSlice: mesSlice.reducer,
        mesSlice2: mesSlice2.reducer
    }
})
export let {
    addMes,
    addNum,
} = mesSlice2.actions

export default store